<?php

if(!isset($_POST['lat']) || !isset($_POST['lng'])){
	if(!isset($_POST['page'])){
		die('You are not allowed to access the pages');
		exit;
	}
}

if(isset($_POST['drag'])){
	$latArr = getLatLngRanges($_POST['lat']);
	$lngArr = getLatLngRanges($_POST['lng']);
	
	$sql = "SELECT a.*,b.id as bid FROM `".ADELAIDE_TABLE."` a INNER JOIN `siteDetails` b ON a.id = b.adKey WHERE  ((`Latitude` BETWEEN '".$latArr['l']."' AND '".$latArr['r']."') AND (`Longitude` BETWEEN '".$lngArr['l']."' AND '".$lngArr['r']."'))";
	$sqlCondition = $_SESSION['sqlConditionForSearching'];
	$sql .= $sqlCondition;
	$totalNums = $dbObj -> getTotalNums($sql);
	$sqlConditionWithoutPrice = $_SESSION['feeSearchedTypeSql'];
	//$totalPages = $_SESSION['sqlPhaseTotalPages'];
}
elseif(isset($_POST['page'])){
	$zPage = $_POST['page'];
	$offset = ($zPage - 1) * RECORD_PER_PAGE;
	$sql = $_SESSION['sqlPhaseForSearching'];
	$sql .= 'LIMIT '.$offset.','.RECORD_PER_PAGE;
	$totalNums = $_SESSION['sqlPhaseTotalNums'];
	$totalPages = $_SESSION['sqlPhaseTotalPages'];
	$currPage = $zPage;
}
else{
	/**
	 * Firstly searching	
	 */
	$latArr = getLatLngRanges($_POST['lat']);
	$lngArr = getLatLngRanges($_POST['lng']);
	//the parking time
	$parkingTime = $_POST['hrs'].$_POST['mins'];
	$parkingLongest = $_POST['parktime'];
	
	$feeType = $_POST['fee'];
	
	if($feeType == 1){
		//FREE
		$sqlCondition = " AND `price` = 0 ";
		$freeIcon = 'N';
	}elseif ($feeType == 2){
		//NOT FREE
		$sqlCondition = " AND `price` > 0 ";
		$freeIcon = 'Y';
	}else{
		//SEARCH ALL
		$sqlCondition = '';
	}
	
	/**
	 * Get the time/day period
	 */
	$weekday = substr($_POST['weekday'], 0,1); 
	switch($weekday){
		case '0'://sun
			$weekday = 2;
		break;
		case '6'://sat
			$weekday = 1;
		break;
		case '8': // ph
			$weekday = substr($_POST['weekday'], 1,1); 
		break;
		default: //(mon-fri)
			$weekday = 0;
		break;
	}
	//$sql = "SELECT * FROM `".ADELAIDE_TABLE."` WHERE  (`Latitude` BETWEEN '".$latArr['l']."' AND '".$latArr['r']."') AND (`Longitude` BETWEEN '".$lngArr['l']."' AND '".$lngArr['r']."')";
	//$sql = "SELECT a.* FROM `".ADELAIDE_TABLE."` a INNERT JOIN `sitedetails` b ON a.id = b.adKey WHERE (`Latitude` BETWEEN '".$latArr['l']."' AND '".$latArr['r']."') AND (`Longitude` BETWEEN '".$lngArr['l']."' AND '".$lngArr['r']."')";
	
	$sql = "SELECT a.*,b.id as bid FROM `".ADELAIDE_TABLE."` a INNER JOIN `siteDetails` b ON a.id = b.adKey WHERE  ((`Latitude` BETWEEN '".$latArr['l']."' AND '".$latArr['r']."') AND (`Longitude` BETWEEN '".$lngArr['l']."' AND '".$lngArr['r']."')) AND
			(`timePeriod`=".$weekday." AND  ((`start` < $parkingTime AND `end` > $parkingTime) AND (`duration` >= $parkingLongest OR `duration`=-1) $sqlCondition) ) ";
	
	//errorEventLog::displaysSQLPhase($sql,PROGRAM_DEBUG);
	$sqlConditionWithoutPrice = " AND (`timePeriod`=".$weekday." AND  ((`start` < $parkingTime AND `end` > $parkingTime) AND (`duration` >= $parkingLongest OR `duration`=-1)))";
	$sqlCondition =  " AND (`timePeriod`=".$weekday." AND  ((`start` < $parkingTime AND `end` > $parkingTime) AND (`duration` >= $parkingLongest OR `duration`=-1) $sqlCondition))"; 
	
	@session_unregister('sqlPhaseForSearching');
	@session_unregister('sqlPhaseTotalNums');
	@session_unregister('sqlPhaseTotalPages');
	@session_unregister('sqlConditionForSearching');
	@session_unregister('feeSearchedTypeSql');
	$_SESSION['sqlPhaseForSearching'] = $sql;
	$_SESSION['sqlConditionForSearching'] = $sqlCondition;
	$totalNums = $dbObj -> getTotalNums($sql);
	$totalPages = ceil ( $totalNums / RECORD_PER_PAGE );
	$currPage = 1;
	$_SESSION['sqlPhaseTotalNums'] = $totalNums;
	$_SESSION['sqlPhaseTotalPages'] = $totalPages;
	$_SESSION['feeSearchedTypeSql'] = $sqlConditionWithoutPrice;
	@session_register('sqlPhaseForSearching');
	@session_register('sqlPhaseTotalNums');
	@session_register('sqlPhaseTotalPages');
	@session_register('sqlConditionForSearching');
	@session_register('feeSearchedTypeSql');
	/**
	 * Loading all the records in one go
	 */
	//$sql .= 'LIMIT 0,'. RECORD_PER_PAGE;
}

$tRecordSet = $dbObj -> executeQuery($sql);
$i = 0;
if($tRecordSet)
{
	$jsonArray='';
	$jsonArray['STATUS'] = 'OK';
	$jsonArray['TOTAL_NUMS'] = $totalNums;
	$jsonArray['TOTAL_PAGE'] = $totalPages;
	$jsonArray['CURR_PAGE'] = $currPage;
	foreach ($tRecordSet as $val)
	{
		if(!isset($freeIcon)||$freeIcon==''){
			$sqlInternal = "SELECT 1 FROM `siteDetails` WHERE `adKey` = '".$val['ID']."' AND `price`= 0 $sqlConditionWithoutPrice";
			$ThisfreeIcon = ($dbObj -> getTotalNums($sqlInternal)>0)?'N':'Y';
			//errorEventLog::displaysSQLPhase($dbObj -> getTotalNums($sqlInternal).'//'.$sqlInternal);
		}else{
			$ThisfreeIcon = $freeIcon;
		}
		$jsonArray['PARKS'][$i]['ADDRESS'] = $val['STREET1'].' '.$val['SUBURB'];
		$jsonArray['PARKS'][$i]['ID'] = $val['ID'];
		$jsonArray['PARKS'][$i]['LAT'] = $val['LATITUDE'];
		$jsonArray['PARKS'][$i]['LNG'] = $val['LONGITUDE'];
		$jsonArray['PARKS'][$i]['NOTES'] =  $val['NOTE'];
		$jsonArray['PARKS'][$i]['TOTAL'] =  $val['TOTAL'];
		$jsonArray['PARKS'][$i]['FEE'] = $ThisfreeIcon;
		$i++;
	}	
	if(is_array($jsonArray)){
		echo json_encode($jsonArray);
	}
}
else{
	$jsonArray['STATUS'] = 'ZERO_RESULTS';
	$jsonArray['TOTAL_PAGE'] = 0;
	$jsonArray['TOTAL_NUMS'] = 0;
	echo json_encode($jsonArray);
}
